package org.example.netty.test.nio.netty.chat.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.test.nio.netty.chat.bean.JoinGroupMessage;
import org.example.netty.test.nio.netty.chat.bean.OutGroupMessage;
import org.example.netty.test.nio.netty.chat.bean.SystemMessage;
import org.example.netty.test.nio.netty.chat.common.SystemMessageType;
import org.example.netty.test.nio.netty.chat.session.GlobalContent;
import org.example.netty.test.nio.netty.chat.session.UserSession;
import org.example.netty.test.nio.netty.chat.util.NettyChannelUtil;

/**
 * @author zp
 * @version 1.0
 * @description: 处理消息JoinGroupMessage
 * @date 2023/4/6 18:29
 */
@Slf4j
public class JoinGroupMessageHandler extends SimpleChannelInboundHandler<JoinGroupMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JoinGroupMessage msg) throws Exception {
        Channel channel = ctx.channel();
        UserSession userSession = NettyChannelUtil.getUserSession(channel);
        GlobalContent globalContent = GlobalContent.getInstance();
        // 获取群名称
        String groupName = msg.getGroupName();
        log.debug("加入群聊的消息：{}", msg);
        // 校验是否已经加入群聊 如果重复 出现报错
        assert userSession != null;
        globalContent.joinGroup(groupName);
        ctx.channel().writeAndFlush(msg);
    }
}
